// import 'dart:io';
//
// import 'package:flutter/material.dart';
// import 'package:hixing_app/assets/r_img.dart';
// import 'package:hixing_app/utils/image_utils.dart';
// import 'package:hixing_app/utils/permission.dart';
// import 'package:image_picker/image_picker.dart';
//
// enum ImgMtxType {
//   original,
//   grey,
//   black,
//   white,
// }
//
// class ResolveArgb extends StatefulWidget {
//   @override
//   _ResolveArgbState createState() => _ResolveArgbState();
// }
//
// class _ResolveArgbState extends State<ResolveArgb> {
//   File? _imgFile;
//   ImgMtxType imgMtxType = ImgMtxType.original;
//
//   // 使用ImagePicker前必须先实例化
//   final ImagePicker picker = ImagePicker();
//
//   Future<void> openGallery() async {
//     bool isImg = await PermissionUtils.requestPhotosStorage();
//
//     final XFile? image = await picker.pickImage(source: ImageSource.gallery);
//     print("选择的图片${image!.name}");
//     setState(() {
//       _imgFile = File(image.path);
//     });
//   }
//
//   Widget _buildColorBox() {
//     Widget child;
//     Widget imgChild = Image.asset(
//       ImgR.imgBgWangzhe,
//     );
//
//     // 反色矩阵
//     const ColorFilter reverseColorMtx = ColorFilter.matrix(<double>[
//       //
//       -1, 0, 0, 0, 255,
//       0, -1, 0, 0, 255,
//       0, 0, -1, 0, 255,
//       0, 0, 0, 1, 0
//     ]);
//     // 灰色矩阵
//     const ColorFilter greyColorMtx = ColorFilter.matrix(<double>[
//       //
//       0.3086, 0.6094, 0.0820, 0, 0,
//       0.3086, 0.6094, 0.0820, 0, 0,
//       0.3086, 0.6094, 0.0820, 0, 0,
//       0, 0, 0, 1, 0
//     ]);
//     //黑白矩阵
//     const double N = 150;
//     const ColorFilter blackColorMtx = ColorFilter.matrix(<double>[
//       //
//       0.3086 * 256, 0.6094 * 256, 0.0820 * 256, 0, -256 * N,
//       0.3086 * 256, 0.6094 * 256, 0.0820 * 256, 0, -256 * N,
//       0.3086 * 256, 0.6094 * 256, 0.0820 * 256, 0, -256 * N,
//       0, 0, 0, 1, 0
//     ]);
//
//     if (imgMtxType == ImgMtxType.original) {
//       child = imgChild;
//     } else {
//       if (imgMtxType == ImgMtxType.grey) {
//         child = ColorFiltered(
//           colorFilter: greyColorMtx,
//           child: imgChild,
//         );
//       } else if (imgMtxType == ImgMtxType.black) {
//         child = ColorFiltered(
//           colorFilter: blackColorMtx,
//           child: imgChild,
//         );
//       } else {
//         print("白色画板====");
//         Widget blackChild = ColorFiltered(
//           colorFilter: blackColorMtx,
//           child: imgChild,
//         );
//         child = ColorFiltered(colorFilter: reverseColorMtx, child: blackChild);
//       }
//     }
//
//     return child;
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text('图片提取ARGB，以及 黑白/灰度处理'),
//       ),
//       body: Center(
//         child: Column(
//           children: [
//             _imgFile == null ? SizedBox.shrink() : Image.file(_imgFile!),
//             _buildColorBox(),
//             TextButton(
//               onPressed: () {
//                 imgMtxType = imgMtxType == ImgMtxType.black
//                     ? ImgMtxType.white
//                     : ImgMtxType.black;
//                 setState(() {});
//               },
//               child: Text("黑白画=>反色"),
//               style: ButtonStyle(
//                   backgroundColor: MaterialStateProperty.all(Colors.black26)),
//             ),
//             TextButton(
//               onPressed: () {
//                 imgMtxType = ImgMtxType.black;
//
//                 setState(() {});
//               },
//               style: ButtonStyle(
//                   backgroundColor: MaterialStateProperty.all(Colors.black26)),
//               child: Text("黑白画"),
//             ),
//             TextButton(
//               onPressed: () {
//                 imgMtxType = ImgMtxType.grey;
//
//                 setState(() {});
//               },
//               style: ButtonStyle(
//                   backgroundColor: MaterialStateProperty.all(Colors.black26)),
//               child: Text("灰度"),
//             ),
//             TextButton(
//               onPressed: () {
//                 imgMtxType = ImgMtxType.original;
//                 setState(() {});
//               },
//               style: ButtonStyle(
//                   backgroundColor: MaterialStateProperty.all(Colors.black26)),
//               child: Text("复原"),
//             ),
//             TextButton(
//               onPressed: openGallery,
//               style: ButtonStyle(
//                   backgroundColor: MaterialStateProperty.all(Colors.black26)),
//               child: Text("选择图片"),
//             )
//           ],
//         ),
//       ),
//     );
//   }
// }

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hixing_app/utils/export_utils.dart';
import 'package:hixing_app/utils/permission.dart';
import 'package:hixing_app/utils/utils.dart';
import 'package:hixing_app/widgets/toast/toast.dart';

import 'package:image_picker/image_picker.dart';

enum ImgMtxType {
  original,
  grey,
  black,
  white,
  red,
  green,
  blue,
}

class ResolveArgb extends StatefulWidget {
  @override
  _ResolveArgbState createState() => _ResolveArgbState();
}

class _ResolveArgbState extends State<ResolveArgb> {
  File? _imgFile;
  ImgMtxType imgMtxType = ImgMtxType.original;
  Uint8List? pixelList;
  ui.Image? _image;
  ui.Image? _renderImg;
  double tVal = 128;
  int _threshold = 128;
  Timer? timer;
  int nowTime = 0;

  // 使用ImagePicker前必须先实例化
  final ImagePicker picker = ImagePicker();

  Future<void> openGallery() async {
    bool isImg = await PermissionUtils.requestPhotosStorage();

    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    print("选择的图片${image!.name}");
    File imageFile = File(image.path);
    ByteData _data = imageFile.readAsBytesSync().buffer.asByteData();
    _loadImage(_data);
    setState(() {
      _imgFile = File(image.path);
      // pxImg = imgData1;
    });

    // imageRaw.forEach((element) {});
  }

  Future<void> _loadImage(ByteData byteData) async {
    // ByteData data = await rootBundle.load('assets/sample_image.png');
    Uint8List bytes = byteData.buffer.asUint8List();
    ui.Codec codec = await ui.instantiateImageCodec(bytes);
    ui.FrameInfo frameInfo = await codec.getNextFrame();
    setState(() {
      _image = frameInfo.image;
    });
    Uint8List? _pixelList = await _getImageData();
    pixelList = _pixelList;
    // print(_pixelList!.length);
    // 16个数组，循环4次
    // var greyList = greyPixelConvert(Uint8List.fromList(
    //     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]));
    // print(greyList); //处理后的灰色数组
  }

  Uint8List pixelColorConvert(Uint8List pxList,
      {ImgMtxType type = ImgMtxType.grey, int threshold = 128}) {
    int splitNum = 4;
    List<int> _pList = [];
    for (int i = 0; i < pxList.length / splitNum; i++) {
      int R = pxList[i * splitNum];
      int G = pxList[i * splitNum + 1];
      int B = pxList[i * splitNum + 2];
      int A = pxList[i * splitNum + 3];

      // _greyList.addAll([greyColor, greyColor, greyColor, A]);
      switch (type) {
        case ImgMtxType.grey:
          int greyColor = (R + G + B) ~/ 3;
          // 灰色通道
          _pList.addAll([greyColor, greyColor, greyColor, A]);
          break;
        case ImgMtxType.red:
          // 红色通道
          _pList.addAll([255, G, B, A]);
        case ImgMtxType.green:
          // 红色通道
          _pList.addAll([R, 255, B, A]);
        case ImgMtxType.blue:
          // 红色通道
          _pList.addAll([R, G, 255, A]);
        case ImgMtxType.black:
          // 阈值通道：黑色:只需要判断R的值就可以
          int bR = R > threshold ? 255 : 0;
          int bG = R > threshold ? 255 : 0;
          int bB = R > threshold ? 255 : 0;
          // 黑255
          _pList.addAll([bR, bG, bB, A]);
        default:
          int saturation = 0;
          // 阈值通道：白色:只需要判断R的值就可以
          int wR = R < threshold ? 255 : saturation;
          int wG = R < threshold ? 255 : saturation;
          int wB = R < threshold ? 255 : saturation;
          // 白色通道
          _pList.addAll([wR, wG, wB, A]);
          break;
      }
    }

    // print("R: $R,G: $G, B:$B,A:$A");
    return Uint8List.fromList(_pList);
  }

  toGenImg(ImgMtxType type) {
    if (pixelList == null) {
      AppToast.showText("请选择图片");
      return;
    }
    setState(() {
      imgMtxType = type;
    });
    nowTime = DateTime.now().millisecondsSinceEpoch;
    var _genList =
        pixelColorConvert(pixelList!, type: type, threshold: _threshold);

    drawPixelList(_genList);
  }

  drawPixelList(Uint8List pxList) {
    ui.decodeImageFromPixels(
        pxList, _image!.width, _image!.height, ui.PixelFormat.rgba8888,
        (result) {
      // 存时间戳 看转换时间
      print("转化之后的图片==== :${result}");
      setState(() {
        _renderImg = result;
      });
    });
  }

  Future<Uint8List?> _getImageData() async {
    if (_image != null) {
      ByteData? byteData =
          await _image!.toByteData(format: ui.ImageByteFormat.rawRgba);
      return byteData!.buffer.asUint8List();
    }
    return null;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('图片提取ARGB，以及 黑白/灰度处理'),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: [
              _imgFile == null ? SizedBox.shrink() : Image.file(_imgFile!),
              _renderImg == null
                  ? const SizedBox.shrink()
                  : Container(
                      child: CustomPaint(
                        size: Size(250, 250), // 设置画布大小
                        painter: RenderImgPainter(
                          renderImg: _renderImg!,
                        ),
                      ),
                    ),
              Visibility(
                visible: imgMtxType == ImgMtxType.white ||
                    imgMtxType == ImgMtxType.black,
                child: Slider(
                  value: tVal,
                  onChanged: (v) {
                    setState(() {
                      tVal = v;
                    });
                    nowTime = 0;
                    if (timer != null) {
                      timer!.cancel();
                    }
                    timer = Timer(Duration(milliseconds: 800), () {
                      print("slinder 实现一个防抖功能");
                      _threshold = v.toInt();
                      toGenImg(imgMtxType);
                    });
                  },
                  //     (v) {
                  //   setState(() {
                  //     // _threshold = v.toInt();
                  //     // toGenImg(imgMtxType);
                  //   });
                  // },
                  max: 255,
                  min: 0,
                ),
              ),
              Text(
                  "${nowTime == 0 ? "--" : "${DateTime.now().millisecondsSinceEpoch - nowTime}ms"}"),
              Wrap(
                alignment: WrapAlignment.spaceAround,
                spacing: 20,
                children: [
                  TextButton(
                    onPressed: () => toGenImg(ImgMtxType.red),
                    child: Text("红色通道"),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.black26)),
                  ),
                  TextButton(
                    onPressed: () => toGenImg(ImgMtxType.green),
                    child: Text("绿色通道"),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.black26)),
                  ),
                  TextButton(
                    onPressed: () => toGenImg(ImgMtxType.blue),
                    child: Text("蓝色通道"),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.black26)),
                  ),
                  TextButton(
                    onPressed: () => toGenImg(ImgMtxType.grey),
                    child: Text("灰度通道"),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.black26)),
                  ),
                  TextButton(
                    onPressed: () => toGenImg(ImgMtxType.black),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.black26)),
                    child: Text("黑画"),
                  ),
                  TextButton(
                    onPressed: () => toGenImg(ImgMtxType.white),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.black26)),
                    child: Text("白画"),
                  ),
                ],
              ),
              TextButton(
                onPressed: openGallery,
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.black26)),
                child: Text("选择图片"),
              )
            ],
          ),
        ),
      ),
    );
  }
}

class RenderImgPainter extends CustomPainter {
  RenderImgPainter({required this.renderImg});

  ui.Image renderImg;

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    // TODO: implement paint
    // canvas.drawImage(renderImg, Offset(0, 0), paint);
    double cmpWidth = 0;
    double cmpHeight = 0;
    if (renderImg.width > renderImg.height) {
      cmpHeight = (size.width / renderImg.width) * renderImg.height;
    } else if (renderImg.width < renderImg.height) {
      cmpWidth = (size.height / renderImg.height) * renderImg.width;
    }
    // Draw image with scaled width
    canvas.drawImageRect(
      renderImg,
      Rect.fromLTRB(
          0, 0, renderImg.width.toDouble(), renderImg.height.toDouble()),
      // 如果要居中，就调这里的 x，y值
      Rect.fromLTRB(0, 0, cmpWidth == 0 ? size.width : cmpWidth,
          cmpHeight == 0 ? size.height : cmpHeight),
      Paint(),
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
